package com.ws.universal.tools.takephoto.multipleimageselect.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.barlibrary.ImmersionBar;
import com.ws.universal.tools.R;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.network.JSONFormat;
import com.ws.universal.tools.pictureselect.manage.CollectionManage;
import com.ws.universal.tools.pictureselect.media.MediaFile;
import com.ws.universal.tools.pictureselect.task.LoadAllTask;
import com.ws.universal.tools.pictureselect.task.LoadImageTask;
import com.ws.universal.tools.pictureselect.task.MediaCallBack;
import com.ws.universal.tools.takephoto.multipleimageselect.adapters.CustomAlbumSelectAdapter;
import com.ws.universal.tools.takephoto.multipleimageselect.helpers.ConstantsCode;
import com.ws.universal.tools.takephoto.multipleimageselect.models.Album;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;

/**
 * @author:ws
 * @date: 2020/9/1 11:57
 * @desc 相册选则
 */
public class AlbumSelectActivity extends AppCompatActivity {
    private final String TAG = AlbumSelectActivity.class.getName();
    private ArrayList<Album> albums;
    private RecyclerView gridView;
    private CustomAlbumSelectAdapter customAlbumSelectAdapter;
    private TextView title_text_tv;
    private ProgressBar progressBar;
    private Handler handler;
    private Context context;
    private boolean showVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //沉浸式
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        setContentView(R.layout.activity_album_select);
        context = this;

        title_text_tv = findViewById(R.id.title_text_tv);
        title_text_tv.setText(getResources().getString(R.string.album_view));
        findViewById(R.id.title_left_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        Intent intent = getIntent();
        if (intent == null) {
            finish();
        }
        if (albums == null) {
            albums = new ArrayList<>();
        }
        showVideo = intent.getBooleanExtra(ConstantsCode.showVideo, false);
        ConstantsCode.limit = intent.getIntExtra(ConstantsCode.INTENT_EXTRA_LIMIT, ConstantsCode.DEFAULT_LIMIT);
        if (customAlbumSelectAdapter == null) {
            customAlbumSelectAdapter = new CustomAlbumSelectAdapter(context);
        }
        gridView = findViewById(R.id.grid_view_album_select);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2);
        gridView.setLayoutManager(gridLayoutManager);
        gridView.setAdapter(customAlbumSelectAdapter);

        customAlbumSelectAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent intent = new Intent(getApplicationContext(), ImageSelectActivity.class);
                intent.putExtra(ConstantsCode.INTENT_EXTRA_ALBUM, customAlbumSelectAdapter.getData().get(position).name);
                //LogcatUtils.e(" album "+albums.get(position).name);
                intent.putExtra(ConstantsCode.showVideo, showVideo);
                startActivityForResult(intent, BusCode.RequestCode_Photo);
            }
        });

        progressBar = findViewById(R.id.progress_bar_album_select);

        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ConstantsCode.PERMISSION_DENIED: {


                        progressBar.setVisibility(View.INVISIBLE);
                        gridView.setVisibility(View.INVISIBLE);

                        break;
                    }

                    case ConstantsCode.FETCH_STARTED: {
                        progressBar.setVisibility(View.VISIBLE);
                        gridView.setVisibility(View.INVISIBLE);

                        break;
                    }
                    case ConstantsCode.FETCH_COMPLETED: {
                        progressBar.setVisibility(View.INVISIBLE);
                        gridView.setVisibility(View.VISIBLE);
                        customAlbumSelectAdapter.setList(albums);
                        break;
                    }
                    case ConstantsCode.ERROR: {
                        progressBar.setVisibility(View.INVISIBLE);
                        break;
                    }
                }
            }
        };
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        albums = null;

    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == BusCode.RequestCode_Photo && data != null) {
            setResult(BusCode.RequestCode_Photo, data);
            finish();
        }
    }


    /**
     * 获取数据
     */
    private void initData() {

        Runnable runnableTask = null;

        if (!showVideo) {//只加载图片
            //
            runnableTask = new LoadImageTask(this, new CallBackData());
            //        } else if (showVideo && !showImage) {//只加载视频
            //            runnableTask = new LoadVideoTask(this, new CallBackData());

        } else {//全部加载
            runnableTask = new LoadAllTask(this, new CallBackData());
        }
        new Thread(runnableTask).start();
    }

    /**
     * 返回数据的接口
     */
    class CallBackData implements MediaCallBack {

        @Override
        public void resultArrayList(final ArrayList<MediaFile> list) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Message message;
                    if (customAlbumSelectAdapter.getData() == null) {
                        message = handler.obtainMessage();
                        message.what = ConstantsCode.FETCH_STARTED;
                        message.sendToTarget();
                    }
                    if (Thread.interrupted()) {
                        return;
                    }
                    CollectionManage.getInstance().setAllList(list);

                    ArrayList<Album> temp = new ArrayList<>();
                    HashSet<String> albumSet = new HashSet<>();
                    File file;
                    LogcatUtils.e(" " + JSONFormat.format(GsonUtils.toJsonObjectSerializeNulls(list.toString()).toString()));
                    for (int i = 0; i < list.size(); i++) {
                        String album = list.get(i).getFolderName();
                        String image = list.get(i).getPath();
                        String type = list.get(i).getMime();
                        file = new File(list.get(i).getPath());
                        if (file.exists() && !albumSet.contains(album)) {
                            temp.add(new Album(album, image, type));
                            albumSet.add(album);
                        }


                    }
                    albums.clear();
                    LogcatUtils.e(" albumSet " + albumSet.size());
                    albums.addAll(temp);
                    message = handler.obtainMessage();
                    message.what = ConstantsCode.FETCH_COMPLETED;
                    message.sendToTarget();
                }
            });

        }
    }


}
